<?php

class Company_AdminController extends Ac_AdminController
{

    public function dashboardAction()
    {
        
        
        if(!empty($_GET['from']) && !empty($_GET['to']))
		{
			$from = new MongoDate (strtotime($_GET['from']." 00:00:01"));
			$to = new MongoDate (strtotime($_GET['to']." 23:59:59"));
			
        	$this->view->num_active_company = Model_Company::all(array('st' => Model_Company::STATUS_ACTIVE, 'cn' => array('$exists' => true), 'bc' => array('$exists' => true), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        $this->view->num_banned_company = Model_Company::all(array('st' => Model_Company::STATUS_DELETED, 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
	        //pending biz w/o company name or biz cat
	        $this->view->num_pending_company = Model_Company::all(array('$or' => array(array('cn' => array('$exists' => false)), array('bc' => array('$exists' => false))), 'c_dt' => array('$gte' => $from, '$lte' => $to)))->count();
        }else
        {
			$this->view->num_active_company = Model_Company::all(array('st' => Model_Company::STATUS_ACTIVE, 'cn' => array('$exists' => true), 'bc' => array('$exists' => true)))->count();
	        $this->view->num_banned_company = Model_Company::all(array('st' => Model_Company::STATUS_DELETED))->count();
	        //pending biz w/o company name or biz cat
	        $this->view->num_pending_company = Model_Company::all(array('$or' => array(array('cn' => array('$exists' => false)), array('bc' => array('$exists' => false)))))->count();
		}
    }

    public function menuAction()
    {
        $this->view->index = $this->_getParam('index');
    }

    public function indexAction() 
    {
        $this->listAction();
    }
    
    public function listAction() 
    {
        $solr = Ac_Search::getClient();

        $_GET['sort'] = $sort = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 30;
        $query = '';
        if (!empty($_GET['company'])) {
            $query = ' username:'.$_GET['company'].' OR email:'.$_GET['company'];
        }
        else {
            $query = '*:*';
        }
        $fields = array();
        $additionalParameters = array();
        
        $this->processRefineSearchForm($page, $per_page, $sort, $query, $fields, $additionalParameters);
        
        $start = ($page-1) * $per_page;
        $list  = $solr->search($query, $start, $per_page, $additionalParameters);
		
		//print_r($additionalParameters);
		
        //$this->view->list    = Model_Listing::all()->limit(50);
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->render('list');
    }
    
    public function editAction()
    {
        /*
        $key    = $_POST['id'];
        $value  = $_POST['val'];
        $locale = $_POST['loc'];
        Model_Translate::addTranslation($key, $value, $locale);
         * 
         */
        echo 'ok';exit;
    }

    public function displayAction()
    {
        $company = Model_Company::find($_GET['id']);
        
        if(isset($_POST['update']))
		{
			$pp = '';
	        $uploads_dir = PUBLIC_PATH.'/images/photo/original/images/profilepic/company';
	        foreach ($_FILES as $key => $file) {
	            if ($file["error"] == UPLOAD_ERR_OK) {
	                $tmp_name = $file["tmp_name"];
	                $img_name     = $file["name"];
	                //var_dump($tmp_name, $uploads_dir.'/'.$name);
	                move_uploaded_file($tmp_name, $uploads_dir.'/'.$_GET['id']."-".$img_name);
	                if ($key == 'pic') {
	                    $pp = '/images/profilepic/company/'.$_GET['id']."-".$img_name;
	                    $company->im = $pp;
	                } 
	            }
	        }   
	        
	        $company->save();
		}

        $this->view->company = $company;
        $this->render('display');
    }

    public function banAction()
    {
        $listing = Model_Company::find($_GET['id']);
        $listing->status = Model_Company::STATUS_BANNED;
        $listing->save();
        $this->_redirect($this->view->geturl('display','company', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function activateAction()
    {
        //The Company
        $company = Model_Company::find($_GET['id']);
        $company->status = Model_Company::STATUS_ACTIVE;
        $company->save();

        //Users
        $users = Model_User::all(array('cid' => new MongoId($_GET['id'])));
        foreach ($users as $data) {
            $data->status = Model_User::STATUS_ACTIVE;
            $data->save();

            //Ads
            $listing = Model_Listing::all(array('us' => new MongoId($data->_id)));
            foreach ($listing as $data) {
                if ($data->status == Model_Listing::STATUS_PUBLISHED_DELETED) {
                    $data->status = Model_Listing::STATUS_PUBLISHED;
                    $data->save();
                }
            }
        }
        $this->_redirect($this->view->geturl('display','company', null, 'admin1', array('id'=> $_GET['id'])));
    }

    public function deleteAction()
    {
        //The Company
        $company = Model_Company::find($_GET['id']);
        $company->deleteCompany();        

        //Users
        $users = Model_User::all(array('cid' => new MongoId($_GET['id'])));
        foreach ($users as $data) {
            $data->deleteUser();
            
            //Ads
            $listing = Model_Listing::all(array('us' => new MongoId($data->_id)));
            foreach ($listing as $data) {
                if ($data->status == Model_Listing::STATUS_PUBLISHED) {
                    $data->status = Model_Listing::STATUS_PUBLISHED_DELETED;
                    $data->save();
                }
            }
        }
        $this->_redirect($this->view->geturl('display','company', null, 'admin1', array('id'=> $_GET['id'])));
    }


    private function processRefineSearchForm($page, $per_page, $sort, &$query, &$fields, &$additionalParameters)
    {
        $results = false;

        $values     = array();
        $valuesplus = array();
        $get     = $_GET;

        if (!empty($_GET['keyword'])) {
            $values['firstname']      = strtolower(trim($_GET['keyword']));
            $values['lastname']       = strtolower(trim($_GET['keyword']));
            $values['username']       = strtolower(trim($_GET['keyword']));
        }

        foreach($values as $k => $val) {
          $values[$k] = ' '.$k.':'.$val.' ';
        }

        if (!empty($values)) {
            $query = implode(' ', $values);
        }

        if (empty($query)) {
            $query = '*:*';
        }

        switch ($_GET['sort']) {
            case 'rel':
                $sort = 'score desc';
                break;
            case 'recent':
                $sort = 'created_at desc';
                break;
            case 'status':
                $sort = 'status desc';
                break;
            case 'email':
                $sort = 'email asc';
                break;
            default:
                $_GET['sort'] = 'recent';
                $sort         = 'created_at desc';
        }

        $additionalParameters = array(
            'fl'   => '*,score',
            'sort' => $sort,
        );

        $fq                     = '';
        $valuesplus             = array();
        $valuesplus[] = ' +type_obj:'.Model_Company::TYPE;


        if (!empty($valuesplus)) {
            $fq .= implode(' ', $valuesplus);
        }

        if (!empty($fq)) {
            $additionalParameters['fq'] = $fq;
        }
    }
}